iT邦幫忙

0

【C#】Behavioral Patterns Memento Mode

c#
  • 分享至 

  • xImage
  •  

The Memento design pattern without violating encapsulation, captures and externalizes an object‘s internal state so that the object can be restored to this state later.


備忘錄模式讓程式能捕獲外部的變化並改變內部的狀態,有點像是遊戲讀取存檔的功能~


學習目標: 備忘錄模式的概念及實務

學習難度: ☆☆☆


using System;

namespace ConsoleApp1
{
    public class Player
    {
        int money;

        public int Money
        {
            get { return money; }

            set
            {
                money = value;

                Console.WriteLine("Player's Money = " + money);
            }
        }

        public Memento CreateMemento()
        {
            return (new Memento(money));
        }

        public void SetMemento(Memento memento)
        {
            Console.WriteLine("Return to last data...");

            Money = memento.Money;
        }
    }

    public class Memento
    {
        int money;

        public Memento(int money)
        {
            this.money = money;
        }

        public int Money
        {
            get { return money; }
        }
    }

    public class Storage
    {
        Memento memento;

        public Memento Memento
        {
            set { memento = value; }

            get { return memento; }
        }
    }

    public class MainProgram
    {
        public static void Main(string[] args)
        {
            Player player = new Player();

            player.Money = 100;

            Storage storage = new Storage();

            storage.Memento = player.CreateMemento();

            player.Money = 50;

            player.SetMemento(storage.Memento);
        }
    }
}

參考資料:

https://www.dofactory.com/net/memento-design-pattern


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言